const request = require('request');
const vsprintf = require('sprintf-js').vsprintf;

/**
 * 查询用户信息
 * @param {*} accessToken 
 * @param {*} user 
 */
function fetchUserInfo(accessToken,user){
    return new Promise((resolve,reject) => {
        if(accessToken && user){
            if(typeof(user) === 'string'){
                getUserInfo(accessToken,user).then(res => {
                    resolve(res);
                });
            }else{
                let uLen = user.length,zl = 0,userMap = {};
                for(let u of user){
                    getUserInfo(accessToken,u).then( res => {
                        ++zl;
                        userMap[u] = res;
                        if(zl === uLen){
                            resolve(userMap);
                        }
                    }).catch(err =>{
                        ++zl;
                        if(zl === uLen){
                            resolve(userMap);
                        }
                    });
                }
            }
        }else{
            reject('参数不全');
        }
    });
}

/**
 * 批量获取accesstoken
 * @param {*} wechatInfo 
 */
function fetchWechatAccessToken(wechatInfo,dbCof = {}){
    return new Promise((resolve,rejcet) => {
        let wL = wechatInfo.length;
        if(wL){
            let zl = 0,wechatAccessTokenMap = {};
            for(let we of wechatInfo){
                _getAccessTokenOfCps(we.appid,we.appsecret,dbCof.auth_url,dbCof.open_platform,dbCof.is_cps).then(res => {
                    ++zl;
                    wechatAccessTokenMap[we.appid] = Object.assign(we,{accessToken:res});
                    if(zl === wL){
                        resolve(wechatAccessTokenMap);
                    }
                }).catch(err => {
                    ++zl;
                    wechatAccessTokenMap[we.appid] = we;
                    if(zl === wL){
                        resolve(wechatAccessTokenMap);
                    }
                });
            }
        }else{
            rejcet('请传入需要查询的微信信息数组');
        }
    });
}

/**
 * cps平台accessToken获取
 * @param {*} appid 
 * @param {*} appsecret 
 * @param {*} authUrl 
 * @param {*} openPlatFormApi 
 */
function _getAccessTokenOfCps(appid,appsecret,authUrl,openPlatFormApi,isCps){
    return new Promise((resolve,reject) => {
        let url = vsprintf(openPlatFormApi,[appid]);
        if(appsecret){
            url = vsprintf(authUrl,[appid,appsecret]);
        }
        try{
            request(url,(error, response, body) => {
                if(error){
                    console.log(error);
                    resolve('');
                    return;
                }
                const jsonObj = JSON.parse(body);
                if(appsecret){
                    if(isCps){
                        return resolve(jsonObj.accesstoken);
                    }
                    return resolve(jsonObj.data);
                }else{
                    if(jsonObj.success){
                        return resolve(jsonObj.data.authorizer_access_token);
                    }
                }
                resolve('');
            });
        }catch(e){
            resolve('');
        }
    });
}

/**
 * 查询微信用户信息
 * @param {*} accessToken 
 * @param {*} openid 
 */
function getUserInfo(accessToken,openid){
    return new Promise((resolve,rejcet) => {
        if(accessToken && openid){
            let url = `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${accessToken}&openid=${openid}&lang=zh_CN`;
            request(url, (error, response, body) => {
                if(error){
                    console.log(error);
                    rejcet(error);
                    return;
                }
                resolve(body);
            });
        }else{
            reject('参数缺失');
        }
    });
}

module.exports = {
    fetchUserInfo: fetchUserInfo,
    fetchWechatAccessToken: fetchWechatAccessToken,
    getUserInfo: getUserInfo
};



